{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X4cRE8IbIrIV"
   },
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Right now, this requires the current master versions of each. Uncomment the following cell and run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "MOsHUjgdIrIW",
    "outputId": "f84a093e-147f-470e-aad9-80fb51193c8e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting git+https://github.com/huggingface/transformers.git\n",
      "  Cloning https://github.com/huggingface/transformers.git to /tmp/pip-req-build-yv0f75wh\n",
      "  Running command git clone -q https://github.com/huggingface/transformers.git /tmp/pip-req-build-yv0f75wh\n",
      "  Resolved https://github.com/huggingface/transformers.git to commit 3a8a8013adc5802cc302e63e403f0e8925fab0ea\n",
      "  Installing build dependencies ... \u001b[?25ldone\n",
      "\u001b[?25h  Getting requirements to build wheel ... \u001b[?25ldone\n",
      "\u001b[?25h    Preparing wheel metadata ... \u001b[?25ldone\n",
      "\u001b[?25hRequirement already satisfied: numpy>=1.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (1.19.5)\n",
      "Requirement already satisfied: huggingface-hub>=0.0.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (0.0.17)\n",
      "Requirement already satisfied: filelock in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (3.0.12)\n",
      "Requirement already satisfied: tokenizers<0.11,>=0.10.1 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (0.10.3)\n",
      "Requirement already satisfied: tqdm>=4.27 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (4.62.2)\n",
      "Requirement already satisfied: sacremoses in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (0.0.45)\n",
      "Requirement already satisfied: regex!=2019.12.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (2021.8.28)\n",
      "Requirement already satisfied: pyyaml>=5.1 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (5.4.1)\n",
      "Requirement already satisfied: requests in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (2.26.0)\n",
      "Requirement already satisfied: packaging>=20.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from transformers==4.12.0.dev0) (21.0)\n",
      "Requirement already satisfied: typing-extensions in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from huggingface-hub>=0.0.17->transformers==4.12.0.dev0) (3.10.0.2)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from packaging>=20.0->transformers==4.12.0.dev0) (2.4.7)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests->transformers==4.12.0.dev0) (2.0.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests->transformers==4.12.0.dev0) (1.26.6)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests->transformers==4.12.0.dev0) (3.2)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests->transformers==4.12.0.dev0) (2021.5.30)\n",
      "Requirement already satisfied: joblib in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from sacremoses->transformers==4.12.0.dev0) (1.0.1)\n",
      "Requirement already satisfied: six in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from sacremoses->transformers==4.12.0.dev0) (1.15.0)\n",
      "Requirement already satisfied: click in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from sacremoses->transformers==4.12.0.dev0) (8.0.1)\n",
      "Collecting git+https://github.com/huggingface/datasets.git\n",
      "  Cloning https://github.com/huggingface/datasets.git to /tmp/pip-req-build-wt1i2fx6\n",
      "  Running command git clone -q https://github.com/huggingface/datasets.git /tmp/pip-req-build-wt1i2fx6\n",
      "  Resolved https://github.com/huggingface/datasets.git to commit 9675a5a1e7b99a86f9c250f6ea5fa5d1e6d5cc7d\n",
      "Requirement already satisfied: numpy>=1.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (1.19.5)\n",
      "Requirement already satisfied: pyarrow!=4.0.0,>=1.0.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (5.0.0)\n",
      "Requirement already satisfied: dill in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (0.3.4)\n",
      "Requirement already satisfied: pandas in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (1.3.2)\n",
      "Requirement already satisfied: requests>=2.19.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (2.26.0)\n",
      "Requirement already satisfied: tqdm>=4.62.1 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (4.62.2)\n",
      "Requirement already satisfied: xxhash in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (2.0.2)\n",
      "Requirement already satisfied: multiprocess in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (0.70.12.2)\n",
      "Requirement already satisfied: fsspec[http]>=2021.05.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (2021.8.1)\n",
      "Requirement already satisfied: aiohttp in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (3.7.4.post0)\n",
      "Requirement already satisfied: huggingface_hub<0.1.0,>=0.0.14 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (0.0.17)\n",
      "Requirement already satisfied: packaging in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from datasets==1.12.2.dev0) (21.0)\n",
      "Requirement already satisfied: typing-extensions in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from huggingface_hub<0.1.0,>=0.0.14->datasets==1.12.2.dev0) (3.10.0.2)\n",
      "Requirement already satisfied: filelock in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from huggingface_hub<0.1.0,>=0.0.14->datasets==1.12.2.dev0) (3.0.12)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from packaging->datasets==1.12.2.dev0) (2.4.7)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests>=2.19.0->datasets==1.12.2.dev0) (1.26.6)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests>=2.19.0->datasets==1.12.2.dev0) (2021.5.30)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests>=2.19.0->datasets==1.12.2.dev0) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from requests>=2.19.0->datasets==1.12.2.dev0) (3.2)\n",
      "Requirement already satisfied: async-timeout<4.0,>=3.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from aiohttp->datasets==1.12.2.dev0) (3.0.1)\n",
      "Requirement already satisfied: chardet<5.0,>=2.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from aiohttp->datasets==1.12.2.dev0) (4.0.0)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from aiohttp->datasets==1.12.2.dev0) (5.1.0)\n",
      "Requirement already satisfied: attrs>=17.3.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from aiohttp->datasets==1.12.2.dev0) (21.2.0)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from aiohttp->datasets==1.12.2.dev0) (1.6.3)\n",
      "Requirement already satisfied: python-dateutil>=2.7.3 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from pandas->datasets==1.12.2.dev0) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2017.3 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from pandas->datasets==1.12.2.dev0) (2021.1)\n",
      "Requirement already satisfied: six>=1.5 in /home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages (from python-dateutil>=2.7.3->pandas->datasets==1.12.2.dev0) (1.15.0)\n"
     ]
    }
   ],
   "source": [
    "#! pip install git+https://github.com/huggingface/transformers.git\n",
    "#! pip install git+https://github.com/huggingface/datasets.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.\n",
    "\n",
    "To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow.\n",
    "\n",
    "First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then uncomment the following cell and input your username and password (this only works on Colab, in a regular notebook, you need to do this in a terminal):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Login successful\n",
      "Your token has been saved to /home/matt/.huggingface/token\n"
     ]
    }
   ],
   "source": [
    "from huggingface_hub import notebook_login\n",
    "\n",
    "notebook_login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !apt install git-lfs\n",
    "# !git config --global user.email \"you@example.com\"\n",
    "# !git config --global user.name \"Your Name\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Make sure your version of Transformers is at least 4.8.1 since the functionality was introduced in that version:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4.12.0.dev0\n"
     ]
    }
   ],
   "source": [
    "import transformers\n",
    "\n",
    "print(transformers.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HFASsisvIrIb"
   },
   "source": [
    "You can find a script version of this notebook to fine-tune your model in a distributed fashion using multiple GPUs or TPUs [here](https://github.com/huggingface/transformers/tree/master/examples/language-modeling)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a3KD3WXU3l-O"
   },
   "source": [
    "# Fine-tuning a language model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JAscNNUD3l-P"
   },
   "source": [
    "In this notebook, we'll see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model on a language modeling tasks. We will cover two types of language modeling tasks which are:\n",
    "\n",
    "- Causal language modeling: the model has to predict the next token in the sentence (so the labels are the same as the inputs shifted to the right). To make sure the model does not cheat, it gets an attention mask that will prevent it to access the tokens after token i when trying to predict the token i+1 in the sentence.\n",
    "\n",
    "![Widget inference representing the causal language modeling task](images/causal_language_modeling.png)\n",
    "\n",
    "- Masked language modeling: the model has to predict some tokens that are masked in the input. It still has access to the whole sentence, so it can use the tokens before and after the tokens masked to predict their value.\n",
    "\n",
    "![Widget inference representing the masked language modeling task](images/masked_language_modeling.png)\n",
    "\n",
    "We will see how to easily load and preprocess the dataset for each one of those tasks, and how to use the `Trainer` API to fine-tune a model on it.\n",
    "\n",
    "A script version of this notebook you can directly run on a distributed environment or on TPU is available in our [examples folder](https://github.com/huggingface/transformers/tree/master/examples)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1r_n9OWV3l-Q"
   },
   "source": [
    "## Preparing the dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kswRMhPc3l-Q"
   },
   "source": [
    "For each of those tasks, we will use the [Wikitext 2]() dataset as an example. You can load it very easily with the 🤗 Datasets library."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "n2ZRs1cL3l-R",
    "outputId": "11151c56-be90-4d11-e7df-db85e745ca5c"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Reusing dataset wikitext (/home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "51fdd1f7b3804bb8966e0dc4ece7c6e9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/3 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "datasets = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f1-9jepM3l-W"
   },
   "source": [
    "You can replace the dataset above with any dataset hosted on [the hub](https://huggingface.co/datasets) or use your own files. Just uncomment the following cell and replace the paths with values that will lead to your files:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "uxSaGa_l3l-W"
   },
   "outputs": [],
   "source": [
    "# datasets = load_dataset(\"text\", data_files={\"train\": path_to_train.txt, \"validation\": path_to_validation.txt}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jY1SwIrY3l-a"
   },
   "source": [
    "You can also load datasets from a csv or a JSON file, see the [full documentation](https://huggingface.co/docs/datasets/loading_datasets.html#from-local-files) for more information."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "u3EtYfeHIrIz"
   },
   "source": [
    "To access an actual element, you need to select a split first, then give an index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "X6HrpprwIrIz",
    "outputId": "d7670bc0-42e4-4c09-8a6a-5c018ded7d95"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'text': ' The game \\'s battle system , the BliTZ system , is carried over directly from Valkyira Chronicles . During missions , players select each unit using a top @-@ down perspective of the battlefield map : once a character is selected , the player moves the character around the battlefield in third @-@ person . A character can only act once per @-@ turn , but characters can be granted multiple turns at the expense of other characters \\' turns . Each character has a field and distance of movement limited by their Action Gauge . Up to nine characters can be assigned to a single mission . During gameplay , characters will call out if something happens to them , such as their health points ( HP ) getting low or being knocked out by enemy attacks . Each character has specific \" Potentials \" , skills unique to each character . They are divided into \" Personal Potential \" , which are innate skills that remain unaltered unless otherwise dictated by the story and can either help or impede a character , and \" Battle Potentials \" , which are grown throughout the game and always grant boons to a character . To learn Battle Potentials , each character has a unique \" Masters Table \" , a grid @-@ based skill table that can be used to acquire and link different skills . Characters also have Special Abilities that grant them temporary boosts on the battlefield : Kurt can activate \" Direct Command \" and move around the battlefield without depleting his Action Point gauge , the character Reila can shift into her \" Valkyria Form \" and become invincible , while Imca can target multiple enemy units with her heavy weapon . \\n'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "datasets[\"train\"][10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WHUmphG3IrI3"
   },
   "source": [
    "To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "ur5sNUcZ3l-g"
   },
   "outputs": [],
   "source": [
    "from datasets import ClassLabel\n",
    "import random\n",
    "import pandas as pd\n",
    "from IPython.display import display, HTML\n",
    "\n",
    "\n",
    "def show_random_elements(dataset, num_examples=10):\n",
    "    assert num_examples <= len(\n",
    "        dataset\n",
    "    ), \"Can't pick more elements than there are in the dataset.\"\n",
    "    picks = []\n",
    "    for _ in range(num_examples):\n",
    "        pick = random.randint(0, len(dataset) - 1)\n",
    "        while pick in picks:\n",
    "            pick = random.randint(0, len(dataset) - 1)\n",
    "        picks.append(pick)\n",
    "\n",
    "    df = pd.DataFrame(dataset[picks])\n",
    "    for column, typ in dataset.features.items():\n",
    "        if isinstance(typ, ClassLabel):\n",
    "            df[column] = df[column].transform(lambda i: typ.names[i])\n",
    "    display(HTML(df.to_html()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "1Uk8NROQ3l-k",
    "outputId": "a822dcec-51e3-4dba-c73c-dba9e0301726"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>text</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>= = Reception = = \\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Commandos on board would then disembark and use demolition charges to destroy nearby dock installations , searchlights and gun emplacements . The destroyer would then be blown up , and the second ship would come in and evacuate the ship 's crew and the commandos . At the same time the RAF would carry out a number of diversionary air raids in the area . \\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>In the final ballot on May 19 , 1769 Cardinal Lorenzo Ganganelli was elected to the papacy receiving all votes except of his own , which he gave to Carlo Rezzonico , nephew of Clement XIII and one of the leaders of Zelanti . He took the name of Clement XIV , in honour of Clement XIII , who had elevated him to the cardinalate . \\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Greenberg , Douglas . \" The Middle Colonies in Recent American Historiography , \" William and Mary Quarterly , July 1979 , Vol . 36 Issue 3 , pp 396 – 427 in JSTOR \\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>= = Development and composition = = \\n</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "show_random_elements(datasets[\"train\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CKerdF353l-o"
   },
   "source": [
    "As we can see, some of the texts are a full paragraph of a Wikipedia article while others are just titles or empty lines."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JEA1ju653l-p"
   },
   "source": [
    "## Causal Language modeling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "v5GTGKZS3l-q"
   },
   "source": [
    "For causal language modeling (CLM) we are going to take all the texts in our dataset and concatenate them after they are tokenized. Then we will split them in examples of a certain sequence length. This way the model will receive chunks of contiguous text that may look like:\n",
    "```\n",
    "part of text 1\n",
    "```\n",
    "or \n",
    "```\n",
    "end of text 1 [BOS_TOKEN] beginning of text 2\n",
    "```\n",
    "depending on whether they span over several of the original texts in the dataset or not. The labels will be the same as the inputs, shifted to the left.\n",
    "\n",
    "We will use the [`distilgpt2`](https://huggingface.co/distilgpt2) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=causal-lm) instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "id": "-WGBCO343l-q"
   },
   "outputs": [],
   "source": [
    "model_checkpoint = \"distilgpt2\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5io6fY_d3l-u"
   },
   "source": [
    "To tokenize all our texts with the same vocabulary that was used when training the model, we have to download a pretrained tokenizer. This is all done by the `AutoTokenizer` class:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "iAYlS40Z3l-v"
   },
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rpOiBrJ13l-y"
   },
   "source": [
    "We can now call the tokenizer on all our texts. This is very simple, using the [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map) method from the Datasets library. First we define a function that call the tokenizer on our texts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "lS2m25YM3l-z"
   },
   "outputs": [],
   "source": [
    "def tokenize_function(examples):\n",
    "    return tokenizer(examples[\"text\"], truncation=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "M9xVAa3s3l-2"
   },
   "source": [
    "Then we apply it to all the splits in our `datasets` object, using `batched=True` and 4 processes to speed up the preprocessing. We won't need the `text` column afterward, so we discard it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "id": "NVAO0H8u3l-3",
    "outputId": "30d88b8a-e353-4e13-f709-8e5e06ef747b"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-45c45540ee29f5f8.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-33c92a880bcb256c.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-0a113dece57f05d5.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-50d10fb517112e6c.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-b1cf02c782604851.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-f0285415f6681109.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-887c03b35991ba7a.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-9f2b6807065ef982.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-8ef26e13ecb47846.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-127ec1f4b0374dda.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-83bceb708fa1a7d6.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-49c4256c684689b5.arrow\n"
     ]
    }
   ],
   "source": [
    "tokenized_datasets = datasets.map(\n",
    "    tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8qik3J_C3l-7"
   },
   "source": [
    "If we now look at an element of our datasets, we will see the text have been replaced by the `input_ids` the model will need:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "id": "nYv_mcKk3l-7",
    "outputId": "8334734c-0f86-4e18-ec17-4216a2d5dd18"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1],\n",
       " 'input_ids': [796, 569, 18354, 7496, 17740, 6711, 796, 220, 198]}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenized_datasets[\"train\"][1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "obvgcXda3l--"
   },
   "source": [
    "Now for the harder part: we need to concatenate all our texts together then split the result in small chunks of a certain `block_size`. To do this, we will use the `map` method again, with the option `batched=True`. This option actually lets us change the number of examples in the datasets by returning a different number of examples than we got. This way, we can create our new samples from a batch of examples.\n",
    "\n",
    "First, we grab the maximum length our model was pretrained with. This might be a big too big to fit in your GPU RAM, so here we take a bit less at just 128."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "id": "DVHs5aCA3l-_"
   },
   "outputs": [],
   "source": [
    "# block_size = tokenizer.model_max_length\n",
    "block_size = 128"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RpNfGiMw3l_A"
   },
   "source": [
    "Then we write the preprocessing function that will group our texts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "id": "iaAJy5Hu3l_B"
   },
   "outputs": [],
   "source": [
    "def group_texts(examples):\n",
    "    # Concatenate all texts.\n",
    "    concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n",
    "    total_length = len(concatenated_examples[list(examples.keys())[0]])\n",
    "    # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n",
    "    # customize this part to your needs.\n",
    "    total_length = (total_length // block_size) * block_size\n",
    "    # Split by chunks of max_len.\n",
    "    result = {\n",
    "        k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n",
    "        for k, t in concatenated_examples.items()\n",
    "    }\n",
    "    result[\"labels\"] = result[\"input_ids\"].copy()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LGJWXtNv3l_C"
   },
   "source": [
    "First note that we duplicate the inputs for our labels. This is because the model of the 🤗 Transformers library apply the shifting to the right, so we don't need to do it manually.\n",
    "\n",
    "Also note that by default, the `map` method will send a batch of 1,000 examples to be treated by the preprocessing function. So here, we will drop the remainder to make the concatenated tokenized texts a multiple of `block_size` every 1,000 examples. You can adjust this behavior by passing a higher batch size (which will also be processed slower). You can also speed-up the preprocessing by using multiprocessing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "id": "gXUSfBrq3l_C",
    "outputId": "34e55885-3d8f-4f05-cbdb-706ce56a25f8"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-06194d2430627d36.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-43af6d422f9edd37.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-e73eb3ae75b953a8.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-000e1f9a78547e06.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-7b90183d7c5571dd.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-f7d6938c832c306f.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-ab9943773b5c757c.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-5a61c0c1d75b7d29.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-0c8e17958f01eb7e.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-8a977fd394fa0d70.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-528862f677682fc7.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-37d1d1ac9dd6c1d0.arrow\n"
     ]
    }
   ],
   "source": [
    "lm_datasets = tokenized_datasets.map(\n",
    "    group_texts,\n",
    "    batched=True,\n",
    "    batch_size=1000,\n",
    "    num_proc=4,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6n84V8Gc3l_G"
   },
   "source": [
    "And we can check our datasets have changed: now the samples contain chunks of `block_size` contiguous tokens, potentially spanning over several of our original texts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "id": "hTeGCLl_3l_G",
    "outputId": "ab381a07-f92e-4b14-f7b6-e4af5513d7c4"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' game and follows the \" Nameless \", a penal military unit serving the nation of Gallia during the Second Europan War who perform secret black operations and are pitted against the Imperial unit \" Calamaty Raven \". \\n The game began development in 2010, carrying over a large portion of the work done on Valkyria Chronicles II. While it retained the standard features of the series, it also underwent multiple adjustments, such as making the game more forgiving for series newcomers. Character designer Raita Honjou and composer Hitoshi Sakimoto both returned from previous entries, along with Valkyria Chronicles II director Takeshi Oz'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.decode(lm_datasets[\"train\"][1][\"input_ids\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iEmeQ7Xm3l_H"
   },
   "source": [
    "Now that the data has been cleaned, we're ready to instantiate our model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "id": "sPqQA3TT3l_I"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "All model checkpoint layers were used when initializing TFGPT2LMHeadModel.\n",
      "\n",
      "All the layers of TFGPT2LMHeadModel were initialized from the model checkpoint at distilgpt2.\n",
      "If your task is similar to the task the model of the checkpoint was trained on, you can already use TFGPT2LMHeadModel for predictions without further training.\n"
     ]
    }
   ],
   "source": [
    "from transformers import TFAutoModelForCausalLM\n",
    "\n",
    "model = TFAutoModelForCausalLM.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VyPQTOF_3l_J"
   },
   "source": [
    "And our optimizer. We can initialize our `AdamWeightDecay` optimizer directly, or we can use the `create_optimizer` function to generate an `AdamWeightDecay` optimizer with a learning rate schedule. In this case, we'll just stick with a constant learning rate for simplicity, so let's just use `AdamWeightDecay`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "id": "jElf8LJ33l_K"
   },
   "outputs": [],
   "source": [
    "from transformers import create_optimizer, AdamWeightDecay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "id": "YbSwEhQ63l_L"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages/keras/optimizer_v2/optimizer_v2.py:355: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we define our loss and compile our model. Note that most models on the Hub compute loss internally, so we actually don't have to specify anything there! Leaving the loss field blank will cause the model to read the `loss` head as its loss value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! Please ensure your labels are passed as the 'labels' key of the input dict so that they are accessible to the model during the forward pass. To disable this behaviour, please pass a loss argument, or explicitly pass loss=None if you do not want your model to compute a loss.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "model.compile(optimizer=optimizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sZRbT9ui3l_N"
   },
   "source": [
    "Next, we convert our datasets to `tf.data.Dataset`, which `Keras` understands natively. `Dataset` objects have a built-in method for this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "id": "OEuqwIra3l_N"
   },
   "outputs": [],
   "source": [
    "train_set = lm_datasets[\"train\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n",
    "    shuffle=True,\n",
    "    batch_size=16,\n",
    ")\n",
    "validation_set = lm_datasets[\"validation\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n",
    "    shuffle=False,\n",
    "    batch_size=16,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6Vvz34Td3l_O"
   },
   "source": [
    "Now we can train our model. We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! Make sure to change the `username` if you do. If you don't want to do this, simply remove the callbacks argument in the call to `fit()`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "id": "NyZvu_MF3l_P",
    "outputId": "b69d0931-7f1f-4f2d-fdb8-09d37c7418bb"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/matt/PycharmProjects/notebooks/examples/model_save is already a clone of https://huggingface.co/Rocketknight1/distilgpt2-finetuned-wikitext2. Make sure you pull the latest changes with `repo.git_pull()`.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1166/1166 [==============================] - 127s 106ms/step - loss: 3.8582 - val_loss: 3.6753\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "48193027fdc04a059deebce19f770443",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload file tf_model.h5:   0%|          | 32.0k/313M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "To https://huggingface.co/Rocketknight1/distilgpt2-finetuned-wikitext2\n",
      "   c0338fb..f08c6b0  main -> main\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x7fadb5881ee0>"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers.keras_callbacks import PushToHubCallback\n",
    "\n",
    "model_name = model_checkpoint.split(\"/\")[-1]\n",
    "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n",
    "username = \"Rocketknight1\"\n",
    "\n",
    "callback = PushToHubCallback(\n",
    "    output_dir=\"./clm_model_save\",\n",
    "    tokenizer=tokenizer,\n",
    "    hub_model_id=f\"{username}/{push_to_hub_model_id}\",\n",
    ")\n",
    "\n",
    "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=[callback])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3APq-vUc3l_R"
   },
   "source": [
    "Once the training is completed, we can evaluate our model and get its cross-entropy loss on the validation set like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "id": "diKZnB1I3l_R",
    "outputId": "9b3ac725-0117-4830-f380-a555ee57c8cf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "121/121 [==============================] - 4s 34ms/step - loss: 3.6753\n"
     ]
    }
   ],
   "source": [
    "eval_loss = model.evaluate(validation_set)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quality of language models is often measured in 'perplexity' rather than cross-entropy. To convert to perplexity, we simply raise e to the power of the cross-entropy loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Perplexity: 39.46\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "print(f\"Perplexity: {math.exp(eval_loss):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you saved the model with the callback, you can now share this model with all your friends, family, favorite pets: they can all load it with the identifier `\"your-username/the-name-you-picked\"` so for instance:\n",
    "\n",
    "```python\n",
    "from transformers import AutoModelForCausalLM\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\"sgugger/my-awesome-model\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "q-EIELH43l_T"
   },
   "source": [
    "## Masked language modeling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LWk97-Ny3l_T"
   },
   "source": [
    "For masked language modeling (MLM) we are going to use the same preprocessing as before for our dataset with one additional step: we will randomly mask some tokens (by replacing them by `[MASK]`) and the labels will be adjusted to only include the masked tokens (we don't have to predict the non-masked tokens).\n",
    "\n",
    "We will use the [`distilroberta-base`](https://huggingface.co/distilroberta-base) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=masked-lm) instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "id": "QRTpmyCc3l_T"
   },
   "outputs": [],
   "source": [
    "model_checkpoint = \"distilroberta-base\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "12F1ulgT3l_V"
   },
   "source": [
    "We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "id": "h8RCYcvr3l_V",
    "outputId": "a5ffeb0a-71da-4b27-e57a-c62f1927562e"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-5b0155d5b79fdf3c.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-a33c81d4a7fd891b.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-d14650fdb4d430c9.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-4194902dc2ae0506.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-632b7f8e5e100733.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-46e2a8de2f9d65cf.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-569e4ec1f4cc2187.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-c6a14340aee4e1dc.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-b4c6499235d8d39a.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-32bd0c9b9898c2cd.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-23677a508cb975fb.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-631cccabfc8a1858.arrow\n"
     ]
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n",
    "tokenized_datasets = datasets.map(\n",
    "    tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "MTuy8UUs3l_X"
   },
   "source": [
    "And like before, we group texts together and chunk them in samples of length `block_size`. You can skip that step if your dataset is composed of individual sentences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "id": "LVYPMwEs3l_X",
    "outputId": "e71ed7f1-b182-4643-a8fb-3d731c70e40b"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-5f5263af915ddf6e.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-7fa4e49fcdc4f81b.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-04cc75da498dd5a1.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-b22dee1df6c2ac9c.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-13aef157e4a92752.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-0516e48232bdb17d.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-9b9bff4c76656417.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-75793f580c9b0659.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-b5f9dbd6d6aaaf18.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-4d99425d90616059.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-02fd7a31c3e330ad.arrow\n",
      "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20/cache-97e70af43e002f3c.arrow\n"
     ]
    }
   ],
   "source": [
    "lm_datasets = tokenized_datasets.map(\n",
    "    group_texts,\n",
    "    batched=True,\n",
    "    batch_size=1000,\n",
    "    num_proc=4,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "nFJ49iHJ3l_Z"
   },
   "source": [
    "The rest is very similar to what we had, with two exceptions. First we use a model suitable for masked LM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "id": "PM10A9Za3l_Z",
    "outputId": "fff2d5bb-397d-4d5d-9aa9-933090cb6680"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "All model checkpoint layers were used when initializing TFRobertaForMaskedLM.\n",
      "\n",
      "All the layers of TFRobertaForMaskedLM were initialized from the model checkpoint at distilroberta-base.\n",
      "If your task is similar to the task the model of the checkpoint was trained on, you can already use TFRobertaForMaskedLM for predictions without further training.\n"
     ]
    }
   ],
   "source": [
    "from transformers import TFAutoModelForMaskedLM\n",
    "\n",
    "model = TFAutoModelForMaskedLM.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We redefine our `loss` and `optimizer` as we did with the CLM model, and we compile the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/matt/miniconda3/envs/tensorflow26/lib/python3.9/site-packages/keras/optimizer_v2/optimizer_v2.py:355: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n",
      "  warnings.warn(\n",
      "No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! Please ensure your labels are passed as the 'labels' key of the input dict so that they are accessible to the model during the forward pass. To disable this behaviour, please pass a loss argument, or explicitly pass loss=None if you do not want your model to compute a loss.\n"
     ]
    }
   ],
   "source": [
    "from transformers import create_optimizer, AdamWeightDecay\n",
    "import tensorflow as tf\n",
    "\n",
    "optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)\n",
    "\n",
    "model.compile(optimizer=optimizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "z6uuUnvz3l_b"
   },
   "source": [
    "Finally, we use a special `data_collator`. The `data_collator` is a function that is responsible for taking the samples and batching them in tensors. In the previous example, we had nothing special to do, so we just used the default for this argument. Here we want to randomly mask tokens. We could do it as a pre-processing step (like the tokenization) but then the tokens would always be masked the same way at each epoch. By doing this step inside the `data_collator`, we ensure this random masking is done in a new way each time we go over the data.\n",
    "\n",
    "To do this masking for us, the library provides a `DataCollatorForLanguageModeling`. We can adjust the probability of the masking. Note that our data collators are designed to work for multiple frameworks, so ensure you set the `return_tensors='tf'` argument to get Tensorflow tensors out - you don't want to accidentally get a load of `torch.Tensor` objects in the middle of your nice TF code!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "id": "nRZ-5v_P3l_b"
   },
   "outputs": [],
   "source": [
    "from transformers import DataCollatorForLanguageModeling\n",
    "\n",
    "data_collator = DataCollatorForLanguageModeling(\n",
    "    tokenizer=tokenizer, mlm_probability=0.15, return_tensors=\"tf\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bqHnWcYC3l_d"
   },
   "source": [
    "Now we generate our datasets as before. Remember to pass the `data_collator` you just made to the `collate_fn` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_set = lm_datasets[\"train\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n",
    "    shuffle=True,\n",
    "    batch_size=16,\n",
    "    collate_fn=data_collator,\n",
    ")\n",
    "\n",
    "validation_set = lm_datasets[\"validation\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n",
    "    shuffle=False,\n",
    "    batch_size=16,\n",
    "    collate_fn=data_collator,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now we fit our model! As before, we can use a callback to sync with the hub during training. You can remove this if you don't want to - but be sure to change the `username` if you do!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "id": "V-Y3gNqV3l_d"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Cloning https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2 into local empty directory.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "62ae522f21a74e1bbd309b04d07d7b97",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Download file tf_model.h5:   0%|          | 7.58k/462M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "42d24171b572460b867bcaf5430dbf78",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Clean file tf_model.h5:   0%|          | 1.00k/462M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1201/1201 [==============================] - 127s 102ms/step - loss: 1.9031 - val_loss: 1.6988\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9b8f0c2ae9ba4b3da5774653986a0653",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload file tf_model.h5:   0%|          | 32.0k/462M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "To https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2\n",
      "   970a4c2..14a3cf0  main -> main\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x7fab643f41c0>"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers.keras_callbacks import PushToHubCallback\n",
    "\n",
    "model_name = model_checkpoint.split(\"/\")[-1]\n",
    "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n",
    "username = \"Rocketknight1\"\n",
    "\n",
    "callback = PushToHubCallback(\n",
    "    output_dir=\"./mlm_model_save\",\n",
    "    tokenizer=tokenizer,\n",
    "    hub_model_id=f\"{username}/{push_to_hub_model_id}\",\n",
    ")\n",
    "\n",
    "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=[callback])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KDBi0reX3l_g"
   },
   "source": [
    "Like before, we can evaluate our model on the validation set and compute perplexity. The perplexity is much lower than for the CLM objective because for the MLM objective, we only have to make predictions for the masked tokens (which represent 15% of the total here) while having access to the rest of the tokens. It's thus an easier task for the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "id": "4hSaANqj3l_g",
    "outputId": "eeeb8727-2e27-4aeb-ac71-c98123214661"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "125/125 [==============================] - 4s 31ms/step - loss: 1.6730\n",
      "Perplexity: 5.33\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "eval_results = model.evaluate(validation_set)\n",
    "print(f\"Perplexity: {math.exp(eval_results):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "wY82caEX3l_i"
   },
   "source": [
    "You can now upload the result of the training to the Hub just as before, just execute this instruction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Cloning https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2 into local empty directory.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8ed9fae9b13745ea943403433ec77588",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload file tf_model.h5:   0%|          | 32.0k/462M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "To https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2\n",
      "   978eb50..0d5777a  main -> main\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2/commit/0d5777ac0773bbc1d297a649e31b3df2b5be3355'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_name = model_checkpoint.split(\"/\")[-1]\n",
    "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n",
    "\n",
    "model.push_to_hub(push_to_hub_model_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can now share this model with all your friends, family, favorite pets: they can all load it with the identifier `\"your-username/the-name-you-picked\"` so for instance:\n",
    "\n",
    "```python\n",
    "from transformers import AutoModelForMaskedLM\n",
    "\n",
    "model = AutoModelForMaskedLM.from_pretrained(\"your-username/my-awesome-model\")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "Fine-tune a language model",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
